<template>
  <div class="post">
    <h1 class="tip">发布启事</h1>
    <div class="form">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules"
               v-loading="loading"
               element-loading-text="提交中,如长时间未响应，请尝试刷新……"
               element-loading-spinner="el-icon-loading">
        <el-form-item label="启事标题" prop="title">
          <el-input v-model="form.title" placeholder="例如张三的校园卡..."></el-input>
        </el-form-item>
        <el-form-item label="详细描述" prop="content">
          <el-input type="textarea" v-model="form.content"  placeholder="时间|地点|物品描述"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactNumber">
          <el-input v-model="form.contactNumber" placeholder="qq|wx|电话号码均可"></el-input>
        </el-form-item>
<!--        <el-form-item label="启事类型" prop="type">-->
<!--          <el-radio-group v-model="form.type">-->
<!--            <el-radio label="失物招领"></el-radio>-->
<!--            <el-radio label="寻物启事"></el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-form-item label="启事类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option value="失物招领" label="失物招领"></el-option>
            <el-option value="寻物启事" label="寻物启事"></el-option>
          </el-select>
        </el-form-item>
        <p><span style="color: red;">*</span> 注意：上传图片大小限制为2MB，大于2MB的图片请以截图的形式上传。</p>
        <el-form-item label="物品照片">
          <el-upload
            accept="image/*"
            :on-change="handleChange"
            ref="pictureUpload"
            :class="{ disabled: uploadDisabled }"
            :limit="limitNum"
            action="http://www.nefuswzl.top/nefu/upload/"
            list-type="picture-card"
            :auto-upload="false"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src=file.url
                alt=""
              >
              <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
          <el-button type="primary" @click="onSubmit('form')" class="submitBtn">发布</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import qs from 'qs';
export default {
  data () {
    return {
      form: {
        title: '',
        content: '',
        type: '',
        contactNumber: '',
        imageUrl: '',
      },
      uploadDisabled:false,
      isUpload: false,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      limitNum: 1,
      loading: false,//上传loading提示
      rules: {
        title: [
          {
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字',
            trigger: 'blur'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入详情',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字',
            trigger: 'blur'
          }
        ],
        contactNumber: [
          {
            required: true,
            message: '请输入联系方式',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 30 个字',
            trigger: 'blur'
          }
        ],
        type: {
          required: true,
          message: '请选择启事类型',
          trigger: 'blur'
        }
      },
    }
  },
  methods: {
    // upload改变
    handleChange (file,fileList) {
      this.isUpload = true
      if(fileList.length >= 1){
        this.uploadDisabled = true;
      }
    },
    // 图片数量超过限制
    handleExceed () {
      this.$message.warning('仅支持上传一张图片')
    },
    //限制文件上传类型及大小
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      let arr = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'pdf', 'JPG', 'JPEG', 'PNG', 'GIF', 'BMP', 'PDF']
      if (arr.indexOf(testmsg) === -1) {
        this.$message.error('上传图片格式有误')
        this.loading = false;
        return false//return false就可以在格式大小不符后返回，不调用接口
      }
      //限制上传文件大小为5MB
      const isLt2M = file.size / 1024 / 1024 < 3
      if (!isLt2M) {
       this.$message.error('上传文件大小不能超过 2MB')
        this.loading = false;
        return false
      }
    },
    onSubmit (form) {
      this.loading = true;
      this.$refs[form].validate((valid) => {
        if (valid) {
          // 验证成功要做的事
          if (this.isUpload) {
            this.$refs.pictureUpload.submit();
          } else {
            //没有图片上传 直接上传表单 imageUrl为空
            this.postForm()
          }
        } else {
          this.loading =false
          this.$message.error('发布失败！')
          return false
        }
      })
    },
    handleSuccess (res, file) {
      //有图片上传 返回结果
      this.form.imageUrl = res
      if (res === 0) {
        this.loading = false;
        this.$message.error('图片上传失败，请重试!');
        return false;
      }else {
        //图片上传成功，则开始上传表单
        this.postForm();
      }
    },
    handleRemove () {
      const uploadFiles = this.$refs.pictureUpload.uploadFiles;
      // for (var i = 0; i < uploadFiles.length; i++) {
      //   if (uploadFiles[i].url === file.url) {
      //     uploadFiles.splice(i, 1)
      //   }
      // }
      uploadFiles.splice(0, 1);
      this.isUpload = false;
      this.uploadDisabled = false;
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    //上传表单函数
    postForm () {
     this.axios.post('/php/insert.php', qs.stringify(this.form)).then((response) => {
        this.loading = false;
        this.$message.success('上传成功');
        if(this.form.type === '失物招领'){
          this.$router.push('/')
        }else{
          this.$router.push('/lost')
        }
      }).catch((err) => {
        this.loading =false;
        this.$message.error("上传失败!"+err);
      })
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
  display: none !important;
}
@font-face {
  font-family: myFont;
  src: url("../assets/font/YanShiYouRanXiaoKai.ttf");
}

.tip {
  font-family: myFont, "华文楷体","Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  font-size: 3rem;
}

.post {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 60px;
}

.form {
  width: 50%;
}

.submitBtn{
  margin-top: 10px;
}
/*修复遮罩无法遮罩表单*/

@media (max-width: 600px) {
  .post {
    padding: 0 5%;
  }

  .form {
    width: 100%;
  }
}
</style>
